package com.zcp.notepad;

import com.zcp.notepad.NotePad.Settings;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class PasswordSettingActivity extends PreferenceActivity implements
		OnSharedPreferenceChangeListener {

	private static final String KEY_FOR_PASSWORD_SETTING_PREFERENCE = "edittext_password";

	private Cursor mCursor;
	private static final String[] PASSWORD = new String[] { Settings._ID, // 0
			Settings.PASSWORD // 1
	};

	
	//弹出更改密码窗口
	private void showChangePasswordDialog(){
		LayoutInflater inflater = getLayoutInflater();
		final View layout = inflater.inflate(
				R.layout.password_change_dialog,
				(ViewGroup) findViewById(R.id.dialog_passwod_setting));

		View inputPasswordLayout = layout
				.findViewById(R.id.input_password_line);
		View newPasswordLayout = layout
				.findViewById(R.id.new_password_line);
		View confirmPasswordLayout = layout.findViewById(R.id.confirm_line);
		
		inputPasswordLayout.setVisibility(View.GONE);
		newPasswordLayout.setVisibility(View.VISIBLE);
		confirmPasswordLayout.setVisibility(View.VISIBLE);

		final TextView newPasswordTv = (TextView) layout
				.findViewById(R.id.new_password_text);
		final TextView confirmTv = (TextView) layout
				.findViewById(R.id.confirm_text);
		
		new AlertDialog.Builder(PasswordSettingActivity.this)
		.setTitle(getString(R.string.change_password))
		.setView(layout)
		.setPositiveButton(getString(R.string.input_ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						
						if("".equals(newPasswordTv.getText().toString())){//输入值为空
							Util.setDialogCanDismiss(dialog, false);
							dialog.dismiss();
							Toast.makeText(
									PasswordSettingActivity.this,
									getString(R.string.password_is_null),
									Toast.LENGTH_SHORT)
									.show();
							return;
						}
						
						mCursor = getContentResolver().query(
								NotePad.Settings.CONTENT_URI,
								PASSWORD, null, null, null);
						if (mCursor.moveToFirst()) {
							boolean confirmOk = newPasswordTv
									.getText()
									.toString()
									.equals(confirmTv.getText()
											.toString());
							
							
							if (confirmOk) {//校验输入值相同
								ContentValues values = new ContentValues();
								values.put(Settings.PASSWORD,
										newPasswordTv.getText()
												.toString());
								getContentResolver()
										.insert(NotePad.Settings.CONTENT_URI,
												values);
								
								Util.setDialogCanDismiss(dialog, true);
				                dialog.dismiss();
								Toast.makeText(
										PasswordSettingActivity.this,
										getString(R.string.new_password_change),
										Toast.LENGTH_SHORT).show();
								
							}else{
								newPasswordTv.setText("");
								confirmTv.setText("");
								Util.setDialogCanDismiss(dialog, false);
				                dialog.dismiss();
				                Toast.makeText(
										PasswordSettingActivity.this,
										getString(R.string.wrong_change_password),
										Toast.LENGTH_SHORT)
										.show();
							}
						}
						mCursor.close();
					}
				})
		.setNegativeButton(getString(R.string.input_cancel), 
				clickCancelDialogDismiss()).show();
	}

	/**
	 * 点击cancel关闭窗口
	 * @return
	 */
	private OnClickListener clickCancelDialogDismiss() {
		return new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog,
					int which) {
				
				Util.setDialogCanDismiss(dialog, true);
				dialog.dismiss();
		}
		};
	}
	
	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {

		if (preference.getKey() != null
				&& preference.getKey().equals(
						KEY_FOR_PASSWORD_SETTING_PREFERENCE)) {
			
			LayoutInflater inflater = getLayoutInflater();
			final View layout = inflater.inflate(
					R.layout.password_setting_dialog,
					(ViewGroup) findViewById(R.id.dialog_passwod_setting));

			View inputPasswordLayout = layout
					.findViewById(R.id.input_password_line);
			View newPasswordLayout = layout
					.findViewById(R.id.new_password_line);
			View confirmPasswordLayout = layout.findViewById(R.id.confirm_line);

			final TextView newPasswordTv = (TextView) layout
					.findViewById(R.id.new_password_text);
			final TextView passwordTv = (TextView) layout
					.findViewById(R.id.password_text);
			final TextView confirmTv = (TextView) layout
					.findViewById(R.id.confirm_text);

			mCursor = getContentResolver().query(NotePad.Settings.CONTENT_URI,
					PASSWORD, null, null, null);
			
			if (mCursor.moveToFirst()) {
				inputPasswordLayout.setVisibility(View.VISIBLE);
				// 更改密码时，第一次弹出输入原密码
				new AlertDialog.Builder(this)
						.setTitle(getString(R.string.input_password))
						.setView(layout)
						.setPositiveButton(getString(R.string.input_ok),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										
										if("".equals(passwordTv.getText().toString())){//输入值为空
											Util.setDialogCanDismiss(dialog, false);
							                dialog.dismiss();
							                TextView tv = (TextView)layout.findViewById(R.id.password_tv);
											tv.setText(R.string.password_is_null);
											return;
										}
										
										mCursor = getContentResolver().query(
												NotePad.Settings.CONTENT_URI,
												PASSWORD, null, null, null);
										
										if (mCursor.moveToFirst()) {
											String memoryPassword = mCursor
													.getString(1);
											if (passwordTv.getText().toString().equals(memoryPassword)) {
												Util.setDialogCanDismiss(dialog, true);
								                dialog.dismiss();
												//第二次弹出,更改密码窗口
												showChangePasswordDialog();
											}else{
												passwordTv.setText("");
												Util.setDialogCanDismiss(dialog, false);//输入错误时不关闭
												TextView tv = (TextView)layout.findViewById(R.id.password_tv);
												tv.setText(R.string.wrong_change_password);
											}
										}
									}
								})
						.setNegativeButton(getString(R.string.input_cancel),clickCancelDialogDismiss()).show();
						mCursor.close();

			} else {//首次设置密码
				inputPasswordLayout.setVisibility(View.GONE);
				newPasswordLayout.setVisibility(View.VISIBLE);
				confirmPasswordLayout.setVisibility(View.VISIBLE);

				new AlertDialog.Builder(this)
						.setTitle(getString(R.string.input_password))
						.setView(layout)
						.setPositiveButton(getString(R.string.input_ok),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										
										boolean confirmOk = newPasswordTv
												.getText()
												.toString()
												.equals(confirmTv.getText()
														.toString());
										
										if("".equals(newPasswordTv.getText().toString())){//输入值为空
											Util.setDialogCanDismiss(dialog, false);
							                dialog.dismiss();
							                Toast.makeText(
													PasswordSettingActivity.this,
													getString(R.string.password_is_null),
													Toast.LENGTH_SHORT)
													.show();
							                return;
										}
										
										if (confirmOk) {//校验输入值不能为空且相同
											ContentValues values = new ContentValues();
											values.put(Settings.PASSWORD,
													newPasswordTv.getText()
															.toString());
											getContentResolver()
													.insert(NotePad.Settings.CONTENT_URI,
															values);
											
											Util.setDialogCanDismiss(dialog, true);
							                dialog.dismiss();
											Toast.makeText(
													PasswordSettingActivity.this,
													getString(R.string.new_password_save),
													Toast.LENGTH_SHORT)
													.show();
											
											//设置完变亮
											PreferenceScreen clearPasswodPre = (PreferenceScreen) findPreference("clear_password");
											clearPasswodPre.setEnabled(true);
										}else{
											
											newPasswordTv.setText("");
											confirmTv.setText("");
											Util.setDialogCanDismiss(dialog, false);
							                dialog.dismiss();
											Toast.makeText(
													PasswordSettingActivity.this,
													getString(R.string.wrong_change_password),
													Toast.LENGTH_SHORT)
													.show();
										}
									}
								})
						.setNegativeButton(getString(R.string.input_cancel), clickCancelDialogDismiss()).show();
			}
		}else{//清除密码
			LayoutInflater inflater = getLayoutInflater();
			final View layout = inflater.inflate(
					R.layout.password_setting_dialog,
					(ViewGroup) findViewById(R.id.dialog_passwod_setting));

			View inputPasswordLayout = layout
					.findViewById(R.id.input_password_line);

			final TextView passwordTv = (TextView) layout
					.findViewById(R.id.password_text);
			
			mCursor = getContentResolver().query(NotePad.Settings.CONTENT_URI,
					PASSWORD, null, null, null);
			if (mCursor.moveToFirst()) {
				inputPasswordLayout.setVisibility(View.VISIBLE);
				// 输入密码
				new AlertDialog.Builder(this)
						.setTitle(getString(R.string.input_password))
						.setView(layout)
						.setPositiveButton(getString(R.string.input_ok),
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										
										if("".equals(passwordTv.getText().toString())){//输入值为空
											Util.setDialogCanDismiss(dialog, false);
							                dialog.dismiss();
							                Toast.makeText(
													PasswordSettingActivity.this,
													getString(R.string.password_is_null),
													Toast.LENGTH_SHORT)
													.show();
							                return;
										}
										
										mCursor = getContentResolver().query(
												NotePad.Settings.CONTENT_URI,
												PASSWORD, null, null, null);
										if (mCursor.moveToFirst()) {
											String memoryPassword = mCursor
													.getString(1);
											if (passwordTv.getText().toString()
													.equals(memoryPassword)) {
												Util.clearNotePassword(PasswordSettingActivity.this);
												Util.clearAllNoteLock(PasswordSettingActivity.this);//清除密码的同时把锁全解开
												
												Util.setDialogCanDismiss(dialog, true);
								                dialog.dismiss();
												Toast.makeText(
														PasswordSettingActivity.this,
														getString(R.string.new_password_clear),
														Toast.LENGTH_SHORT)
														.show();
												
												//清除完变灰
												PreferenceScreen clearPasswodPre = (PreferenceScreen) findPreference("clear_password");
												clearPasswodPre.setEnabled(false);
											}else{
												
												passwordTv.setText("");
												Util.setDialogCanDismiss(dialog, false);//输入错误时不关闭
												TextView tv = (TextView)layout.findViewById(R.id.password_tv);
												tv.setText(R.string.wrong_change_password);
											}
										}
									}
								})
						.setNegativeButton(getString(R.string.input_cancel),clickCancelDialogDismiss()).show();
						mCursor.close();
			} 
		}
		return super.onPreferenceTreeClick(preferenceScreen, preference);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.layout.password_setting);

		mCursor = getContentResolver().query(
				NotePad.Settings.CONTENT_URI,
				PASSWORD, null, null, null);
		if (!mCursor.moveToFirst()) {
			PreferenceScreen clearPasswodPre = (PreferenceScreen) findPreference("clear_password");
			clearPasswodPre.setEnabled(false);
		}

	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		// TODO Auto-generated method stub

	}

}
